package com.resou.reader.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.resou.reader.R;
import com.resou.reader.commom.Constant;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import static com.resou.reader.commom.Constant.WX_PAY_SUCCESS;

public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    public static final String TAG = "rs.WXPayEntryActivity";

    private static IWXAPI api;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID_WE_CHAT);
        api.registerApp(Constant.APP_ID_WE_CHAT);
        api.handleIntent(getIntent(), this);
    }

//    @Override
//    protected void initViews() {
//
//    }
//
//    @Override
//    protected void initView() {
//        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID_WE_CHAT);
//        api.registerApp(Constant.APP_ID_WE_CHAT);
//        api.handleIntent(getIntent(), this);
//    }
//
//    @Override
//    public int getLayoutId() {
//        return R.layout.activity_wxpay_entry;
//    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.d(TAG, "guolong 1111" + baseResp.errStr);
        Log.d(TAG, "onPayFinish, errCode = " + baseResp.errCode);

        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            int code = baseResp.errCode;
            if (code == 0) {
                //支付成功后的逻辑处理
//                Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                sendBroadcast(new Intent(WX_PAY_SUCCESS));
            } else if (code == -2) {
                //用户取消
                Toast.makeText(this, R.string.pay_cancel, Toast.LENGTH_SHORT).show();
            } else if (code == -1) {
                //错误
                Toast.makeText(this, R.string.pay_wrong, Toast.LENGTH_SHORT).show();
            }
            finish();
        }
    }

}
